# 导入模块
import sys
# 窗口配置
from PyQt5.QtWidgets import *
# 图像相关
from PyQt5.QtGui import *
# QtCore相关
from PyQt5.QtCore import *
sys.path.append("../")
from ui.Ui_BluetoothTest import Ui_Form
from driver.bluetoothTest import BluetoothDataTransfer
from common.hex_util import *
import threading
import binascii

class MyWidget(QWidget):
    
    receiveDataVerifySignal = pyqtSignal(bytes)
    receiveDataHandleSignal = pyqtSignal(bytes)
    
    def __init__(self, parent = None):
        super().__init__(parent)

        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.bluetoothList = [] # 蓝牙设备列表
        self.deviceAddress = None # 蓝牙设备地址
        self.deviceName = None # 蓝牙设备名称
        self.connectFlag = False # 连接标志

        self.init_ui()

    def init_ui(self):
        # 扫描按钮
        self.ui.scanButton.clicked.connect(self.scanBluetooth)
        # 连接按钮
        self.ui.connectButton.clicked.connect(self.connectBluetooth)
        # 断开连接按钮
        self.ui.disconnectButton.clicked.connect(self.disconnectBluetooth)
        # 发送按钮
        self.ui.sendButton.clicked.connect(self.sendData)
        # 接收并校验数据
        self.receiveDataVerifySignal.connect(self.receiveDataVerifySlot, Qt.AutoConnection)
        # 接收并处理数据
        self.receiveDataHandleSignal.connect(self.receiveDataHandleSlot, Qt.AutoConnection)
        
    # 扫描蓝牙    
    def scanBluetooth(self):
        self.ui.resultEdit.setText("扫描中....")
        threading.Thread(target=self.scanBluetoothThread, daemon=1).start()
    
    # 扫描蓝牙线程
    def scanBluetoothThread(self):
        self.bluetoothList = BluetoothDataTransfer.scan_devices()
        
        self.ui.comboBox.clear()
        for device in self.bluetoothList:
            name = device[1]
            name = name.strip()
            if name != "":
                self.ui.comboBox.addItem(name)
        
        self.ui.comboBox.setCurrentIndex(0)
        self.ui.resultEdit.setText("扫描成功!")    

    # 连接蓝牙
    def connectBluetooth(self):
        name = self.ui.comboBox.currentText()      
        for device in self.bluetoothList:
            if device[1] == name:
                self.deviceAddress, self.deviceName = device

        print("deviceAddress: ", self.deviceAddress, "deviceName: ", self.deviceName)
        self.ui.nameEdit.setText(self.deviceName)
        self.ui.addressEdit.setText(self.deviceAddress)
        self.ui.resultEdit.setText("正在连接....")
        threading.Thread(target=self.connectBluetoothThread, daemon=1).start()
        
    # 连接蓝牙线程    
    def connectBluetoothThread(self):
        
        if self.connectFlag:
            self.BluetoothDataTransfer.disconnect()
            self.ui.connectButton.setText("连接")
            self.connectFlag = False
            return
            
        self.BluetoothDataTransfer = BluetoothDataTransfer(self.deviceAddress, self.deviceName)
        flag = self.BluetoothDataTransfer.connect()
        if flag:
            self.ui.resultEdit.setText("连接成功!")
            self.ui.connectButton.setText("断开(已连接)")
            self.connectFlag = True
            while True:
                receiveData = self.BluetoothDataTransfer.receive_data()

                if receiveData:   
                    self.receiveDataVerifySignal.emit(receiveData)
                else:
                    break
        else:
            self.ui.resultEdit.setText("连接失败!")
    
    # 接收蓝牙数据
    def receiveDataVerifySlot(self, data):
        sum = 0
        length = len(data)
        if data[0] == 0xAA:
            if data[1] == 0x55:
                for i in range(length - 1):
                    sum += data[i]
        if sum == data[length]:
            self.receiveDataHandleSignal.emit(data)
        
    def receiveDataHandleSlot(self, data):
        print("receiveDataHandleSlot: ", data)  
        
    def sendData(self):
        threading.Thread(target=self.sendDataThread, daemon=1).start()
    
    def sendDataThread(self):
        data = self.ui.sendEdit.toPlainText()
        self.BluetoothDataTransfer.send_data(data)
             

if __name__ == '__main__':
    # 创建应用程序
    app = QApplication(sys.argv)

    # 创建窗口
    w = MyWidget()

    # 显示窗口
    w.show()

    # 等待程序结束
    sys.exit(app.exec_())